from datetime import datetime
from app import db


class CommissionRecord(db.Model):
    """佣金记录模型"""
    __tablename__ = 'commission_records'

    id = db.Column(db.Integer, primary_key=True)
    matchmaker_id = db.Column(db.Integer, db.ForeignKey('matchmakers.id', ondelete='CASCADE'), nullable=False, comment='红娘ID')
    user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='SET NULL'), comment='用户ID')
    order_id = db.Column(db.Integer, comment='订单ID')
    record_id = db.Column(db.Integer, comment='相关记录ID（牵线记录、爆灯记录等）')
    commission_type = db.Column(db.String(20), nullable=False, comment='佣金类型：membership会员,matchmaking牵线,light爆灯')
    amount = db.Column(db.Numeric(10, 2), nullable=False, comment='佣金金额')
    rate = db.Column(db.Numeric(5, 2), comment='佣金比例')
    original_amount = db.Column(db.Numeric(10, 2), comment='原始金额')
    status = db.Column(db.Integer, default=1, comment='状态：1冻结2可用3已提现')
    freeze_until = db.Column(db.DateTime, comment='冻结到期时间')
    description = db.Column(db.Text, comment='佣金描述')
    created_at = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')

    # 索引
    __table_args__ = (
        db.Index('idx_matchmaker_id', 'matchmaker_id'),
        db.Index('idx_status', 'status'),
        db.Index('idx_commission_type', 'commission_type'),
        db.Index('idx_created_at', 'created_at'),
    )

    def __repr__(self):
        return f'<CommissionRecord {self.id}>'

    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'matchmaker_id': self.matchmaker_id,
            'user_id': self.user_id,
            'order_id': self.order_id,
            'record_id': self.record_id,
            'commission_type': self.commission_type,
            'commission_type_text': self._get_commission_type_text(),
            'amount': float(self.amount) if self.amount else 0,
            'rate': float(self.rate) if self.rate else 0,
            'original_amount': float(self.original_amount) if self.original_amount else 0,
            'status': self.status,
            'status_text': self._get_status_text(),
            'freeze_until': self.freeze_until.strftime('%Y-%m-%d %H:%M:%S') if self.freeze_until else None,
            'description': self.description,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None
        }
    
    def _get_commission_type_text(self):
        """获取佣金类型文本"""
        type_map = {
            'membership': '会员购买',
            'matchmaking': '牵线服务',
            'light': '爆灯服务'
        }
        return type_map.get(self.commission_type, '未知')
    
    def _get_status_text(self):
        """获取状态文本"""
        status_map = {
            1: '冻结中',
            2: '可提现',
            3: '已提现'
        }
        return status_map.get(self.status, '未知') 